package v1

import (
	"net/http"
	"server/internal/model"
	"server/pkg/app"
	"server/pkg/errcode"
	"server/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

func GetUser(c *gin.Context) *model.Owner {
	user := &model.Owner{
		Name: c.GetString("username"),
	}
	user.Info()
	return user
}

func SetUserInfo(c *gin.Context) int {
	userinfo := GetUser(c)
	return userinfo.ID
}

// 创建用户
func CreateUser(c *gin.Context) {
	_ = c.Request.ParseForm()
	user := &model.User{}
	_ = c.ShouldBind(user)
	if len(user.Name) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": errcode.UserNameNotEmpty,
			"msg":  "用户名不能为空",
		})
		return
	}
	if len(user.PassWord) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": errcode.UserNameNotEmpty,
			"msg":  "密码不能为空",
		})
		return
	}
	if user.Role == "超级管理员" {
		user.Role = "superadmin"
	} else if user.Role == "管理员" {
		user.Role = "admin"
	} else if user.Role == "成员" {
		user.Role = "user"
	} else {
		user.Role = "guest"
	}

	user.PassWord = utils.EncodeMD5(user.PassWord)

	if len(user.Name) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"msg": "用户名不能为空",
		})
		return
	}
	err := user.Create()

	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.String(http.StatusOK, "用户创建成功")
}

// 获取所有用户
func UserList(c *gin.Context) {
	user := model.User{}
	users, total := user.List()
	app.ToResponseList(c, users, total)
}

// 更新用户信息
func ModifyUser(c *gin.Context) {
	// user := c.Query("id")
	_ = c.Request.ParseForm()
	user := &model.User{}
	_ = c.ShouldBind(user)
	if user.Role == "超级管理员" {
		user.Role = "superadmin"
	} else if user.Role == "管理员" {
		user.Role = "admin"
	} else if user.Role == "成员" {
		user.Role = "user"
	} else {
		user.Role = "guest"
	}

	err := user.Update()
	if err != nil {
		c.String(http.StatusOK, err.Error())
		return
	}
	c.String(http.StatusOK, "更新用户信息成功")
}

// 更新用户信息
func UserProject(c *gin.Context) {
	name := c.Param("name")
	u := &model.Owner{}
	u.Name = name
	u.Info()

	c.JSON(http.StatusOK, gin.H{
		"data": u.Projects,
	})
}

// 删除用户
func DeleteUser(c *gin.Context) {
	id := c.Param("id")
	if len(id) == 0 {
		c.JSON(http.StatusConflict, gin.H{
			"msg": "未知用户",
		})
		return
	}
	u := &model.Owner{}
	u.ID, _ = strconv.Atoi(id)
	err := u.Delete()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "用户删除失败",
		})
		return
	}
	c.String(http.StatusOK, "用户删除成功")
}

func GetToken(c *gin.Context) {
	id := c.Param("id")
	u := &model.User{}
	u.ID, _ = strconv.Atoi(id)
	u.Info()
	c.JSON(http.StatusOK, gin.H{
		"token": u.Token,
	})
}
